Security News
Weekly Downloads Now Available in npm Package Search Results
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
leveldown
Advanced tools
LevelDOWN is a Node.js binding for LevelDB, a fast key-value storage library written at Google that provides an ordered mapping from string keys to string values. It is used as a backend for the LevelUP module, which provides a more user-friendly API.
Open a Database
This feature allows you to open a LevelDB database. The code sample demonstrates how to open a database located at './mydb'.
const leveldown = require('leveldown');
const db = leveldown('./mydb');
db.open(function (err) {
if (err) throw err;
console.log('Database opened');
});
Put Data
This feature allows you to store a key-value pair in the database. The code sample shows how to store the value 'value' under the key 'key'.
db.put('key', 'value', function (err) {
if (err) throw err;
console.log('Data written');
});
Get Data
This feature allows you to retrieve a value by its key from the database. The code sample demonstrates how to get the value associated with the key 'key'.
db.get('key', function (err, value) {
if (err) throw err;
console.log('Data retrieved:', value);
});
Delete Data
This feature allows you to delete a key-value pair from the database. The code sample shows how to delete the key 'key' from the database.
db.del('key', function (err) {
if (err) throw err;
console.log('Data deleted');
});
Batch Operations
This feature allows you to perform multiple operations in a single batch. The code sample demonstrates how to perform a batch operation that puts and deletes multiple key-value pairs.
db.batch()
.put('key1', 'value1')
.del('key2')
.put('key3', 'value3')
.write(function (err) {
if (err) throw err;
console.log('Batch operations completed');
});
LevelUP is a higher-level module that provides a more user-friendly API for LevelDB. It uses LevelDOWN as its default backend. Compared to LevelDOWN, LevelUP offers a more convenient and feature-rich interface for interacting with LevelDB.
RocksDB is a high-performance key-value store developed by Facebook. It is similar to LevelDB but offers better performance and more features, such as column families and transactions. The 'rocksdb' npm package provides Node.js bindings for RocksDB.
LMDB (Lightning Memory-Mapped Database) is a fast memory-mapped key-value store. The 'lmdb' npm package provides Node.js bindings for LMDB. Compared to LevelDOWN, LMDB offers better performance for read-heavy workloads and supports ACID transactions.
This module was originally part of levelup
but was later extracted and now serves as a stand-alone binding for LevelDB.
It is strongly recommended that you use levelup
in preference to leveldown
unless you have measurable performance reasons to do so. levelup
is optimised for usability and safety. Although we are working to improve the safety of the leveldown
interface it is still easy to crash your Node process if you don't do things in just the right way.
See the section on safety below for details of known unsafe operations with leveldown
.
We aim to support at least Active LTS and Current Node.js releases. leveldown
ships with prebuilt binaries for many platforms and is known to work on:
When installing leveldown
, prebuild-install
will install prebuilt binaries from GitHub if they exist and fallback to a compile step if they don't. In that case you'll need a valid node-gyp
installation.
If you don't want to use the prebuilt binary for the platform you are installing on, specify the --build-from-source
flag when you install. If you are working on leveldown
itself and want to re-compile the C++ code it's enough to do npm install
.
leveldown()
leveldown#open()
leveldown#close()
leveldown#put()
leveldown#get()
leveldown#del()
leveldown#batch()
leveldown#approximateSize()
leveldown#compactRange()
leveldown#getProperty()
leveldown#iterator()
iterator#next()
iterator#seek()
iterator#end()
leveldown.destroy()
leveldown.repair()
leveldown()
returns a new leveldown
instance. location
is a String pointing to the LevelDB location to be opened.
open()
is an instance method on an existing database object.
The callback
function will be called with no arguments when the database has been successfully opened, or with a single error
argument if the open operation failed for any reason.
options
The optional options
argument may contain:
createIfMissing
(boolean, default: true
): If true
, will initialise an empty database at the specified location if one doesn't already exist. If false
and a database doesn't exist you will receive an error in your open()
callback and your database won't open.
errorIfExists
(boolean, default: false
): If true
, you will receive an error in your open()
callback if the database exists at the specified location.
compression
(boolean, default: true
): If true
, all compressible data will be run through the Snappy compression algorithm before being stored. Snappy is very fast and shouldn't gain much speed by disabling so leave this on unless you have good reason to turn it off.
cacheSize
(number, default: 8 * 1024 * 1024
= 8MB): The size (in bytes) of the in-memory LRU cache with frequently used uncompressed block contents.
Advanced options
The following options are for advanced performance tuning. Modify them only if you can prove actual benefit for your particular application.
writeBufferSize
(number, default: 4 * 1024 * 1024
= 4MB): The maximum size (in bytes) of the log (in memory and stored in the .log file on disk). Beyond this size, LevelDB will convert the log data to the first level of sorted table files. From the LevelDB documentation:Larger values increase performance, especially during bulk loads. Up to two write buffers may be held in memory at the same time, so you may wish to adjust this parameter to control memory usage. Also, a larger write buffer will result in a longer recovery time the next time the database is opened.
blockSize
(number, default 4096
= 4K): The approximate size of the blocks that make up the table files. The size related to uncompressed data (hence "approximate"). Blocks are indexed in the table file and entry-lookups involve reading an entire block and parsing to discover the required entry.
maxOpenFiles
(number, default: 1000
): The maximum number of files that LevelDB is allowed to have open at a time. If your data store is likely to have a large working set, you may increase this value to prevent file descriptor churn. To calculate the number of files required for your working set, divide your total data by 'maxFileSize'
.
blockRestartInterval
(number, default: 16
): The number of entries before restarting the "delta encoding" of keys within blocks. Each "restart" point stores the full key for the entry, between restarts, the common prefix of the keys for those entries is omitted. Restarts are similar to the concept of keyframes in video encoding and are used to minimise the amount of space required to store keys. This is particularly helpful when using deep namespacing / prefixing in your keys.
maxFileSize
(number, default: 2* 1024 * 1024
= 2MB): The maximum amount of bytes to write to a file before switching to a new one. From the LevelDB documentation:
... if your filesystem is more efficient with larger files, you could consider increasing the value. The downside will be longer compactions and hence longer latency/performance hiccups. Another reason to increase this parameter might be when you are initially populating a large database.
close()
is an instance method on an existing database object. The underlying LevelDB database will be closed and the callback
function will be called with no arguments if the operation is successful or with a single error
argument if the operation failed for any reason.
put()
is an instance method on an existing database object, used to store new entries, or overwrite existing entries in the LevelDB store.
The key
and value
objects may either be strings or Buffers. Other object types are converted to strings with the toString()
method. Keys may not be null
or undefined
and objects converted with toString()
should not result in an empty-string. Values of null
, undefined
, ''
, []
and new Buffer(0)
(and any object resulting in a toString()
of one of these) will be stored as a zero-length character array and will therefore be retrieved as either ''
or new Buffer(0)
depending on the type requested.
A richer set of data-types is catered for in levelup
.
options
The only property currently available on the options
object is sync
(boolean, default: false
). If you provide a sync
value of true
in your options
object, LevelDB will perform a synchronous write of the data; although the operation will be asynchronous as far as Node is concerned. Normally, LevelDB passes the data to the operating system for writing and returns immediately, however a synchronous write will use fsync()
or equivalent so your callback won't be triggered until the data is actually on disk. Synchronous filesystem writes are significantly slower than asynchronous writes but if you want to be absolutely sure that the data is flushed then you can use { sync: true }
.
The callback
function will be called with no arguments if the operation is successful or with a single error
argument if the operation failed for any reason.
get()
is an instance method on an existing database object, used to fetch individual entries from the LevelDB store.
The key
object may either be a string or a Buffer and cannot be undefined
or null
. Other object types are converted to strings with the toString()
method and the resulting string may not be a zero-length. A richer set of data-types is catered for in levelup
.
Values fetched via get()
that are stored as zero-length character arrays (null
, undefined
, ''
, []
, new Buffer(0)
) will return as empty-String
(''
) or new Buffer(0)
when fetched with asBuffer: true
(see below).
options
The optional options
object may contain:
fillCache
(boolean, default: true
): LevelDB will by default fill the in-memory LRU Cache with data from a call to get. Disabling this is done by setting fillCache
to false
.
asBuffer
(boolean, default: true
): Used to determine whether to return the value
of the entry as a string or a Buffer. Note that converting from a Buffer to a string incurs a cost so if you need a string (and the value
can legitimately become a UTF8 string) then you should fetch it as one with { asBuffer: false }
and you'll avoid this conversion cost.
The callback
function will be called with a single error
if the operation failed for any reason. If successful the first argument will be null
and the second argument will be the value
as a string or Buffer depending on the asBuffer
option.
del()
is an instance method on an existing database object, used to delete entries from the LevelDB store.
The key
object may either be a string or a Buffer and cannot be undefined
or null
. Other object types are converted to strings with the toString()
method and the resulting string may not be a zero-length. A richer set of data-types is catered for in levelup
.
options
The only property currently available on the options
object is sync
(boolean, default: false
). See leveldown#put() for details about this option.
The callback
function will be called with no arguments if the operation is successful or with a single error
argument if the operation failed for any reason.
batch()
is an instance method on an existing database object. Used for very fast bulk-write operations (both put and delete). The operations
argument should be an Array
containing a list of operations to be executed sequentially, although as a whole they are performed as an atomic operation inside LevelDB.
Each operation is contained in an object having the following properties: type
, key
, value
, where the type is either 'put'
or 'del'
. In the case of 'del'
the 'value'
property is ignored. Any entries with a 'key'
of null
or undefined
will cause an error to be returned on the callback
. Any entries where the type is 'put'
that have a 'value'
of undefined
, null
, []
, ''
or new Buffer(0)
will be stored as a zero-length character array and therefore be fetched during reads as either ''
or new Buffer(0)
depending on how they are requested.
See levelup
for full documentation on how this works in practice.
options
The only property currently available on the options
object is sync
(boolean, default: false
). See leveldown#put() for details about this option.
The callback
function will be called with no arguments if the operation is successful or with a single error
argument if the operation failed for any reason.
approximateSize()
is an instance method on an existing database object. Used to get the approximate number of bytes of file system space used by the range [start..end)
. The result may not include recently written data.
The start
and end
parameters may be strings or Buffers representing keys in the LevelDB store.
The callback
function will be called with no arguments if the operation is successful or with a single error
argument if the operation failed for any reason.
compactRange()
is an instance method on an existing database object. Used to manually trigger a database compaction in the range [start..end)
.
The start
and end
parameters may be strings or Buffers representing keys in the LevelDB store.
The callback
function will be called with no arguments if the operation is successful or with a single error
argument if the operation failed for any reason.
getProperty
can be used to get internal details from LevelDB. When issued with a valid property string, a readable string will be returned (this method is synchronous).
Currently, the only valid properties are:
'leveldb.num-files-at-levelN'
: return the number of files at level N, where N is an integer representing a valid level (e.g. "0").
'leveldb.stats'
: returns a multi-line string describing statistics about LevelDB's internal operation.
'leveldb.sstables'
: returns a multi-line string describing all of the sstables that make up contents of the current database.
iterator()
is an instance method on an existing database object. It returns a new Iterator instance.
options
The optional options
object may contain:
gt
(greater than), gte
(greater than or equal) define the lower bound of the values to be fetched and will determine the starting point where reverse
is not true
. Only records where the key is greater than (or equal to) this option will be included in the range. When reverse
is true
the order will be reversed, but the records returned will be the same.
lt
(less than), lte
(less than or equal) define the higher bound of the range to be fetched and will determine the starting point where reverse
is not true
. Only records where the key is less than (or equal to) this option will be included in the range. When reverse
is true
the order will be reversed, but the records returned will be the same.
start, end
legacy ranges - instead use gte, lte
reverse
(boolean, default: false
): a boolean, set to true
if you want the stream to go in reverse order. Beware that due to the way LevelDB works, a reverse seek will be slower than a forward seek.
keys
(boolean, default: true
): whether the callback to the next()
method should receive a non-null key
. There is a small efficiency gain if you ultimately don't care what the keys are as they don't need to be converted and copied into JavaScript.
values
(boolean, default: true
): whether the callback to the next()
method should receive a non-null value
. There is a small efficiency gain if you ultimately don't care what the values are as they don't need to be converted and copied into JavaScript.
limit
(number, default: -1
): limit the number of results collected by this iterator. This number represents a maximum number of results and may not be reached if you get to the end of the store or your end
value first. A value of -1
means there is no limit.
fillCache
(boolean, default: false
): whether LevelDB's LRU-cache should be filled with data read.
keyAsBuffer
(boolean, default: true
): Used to determine whether to return the key
of each entry as a string or a Buffer. Note that converting from a Buffer to a string incurs a cost so if you need a string (and the value
can legitimately become a UTF8 string) then you should fetch it as one.
valueAsBuffer
(boolean, default: true
): Used to determine whether to return the value
of each entry as a string or a Buffer.
next()
is an instance method on an existing iterator object, used to increment the underlying LevelDB iterator and return the entry at that location.
the callback
function will be called with no arguments in any of the following situations:
end
key has been reached; orlimit
has been reached; orseek()
was out of rangeOtherwise, the callback
function will be called with the following 3 arguments:
error
- any error that occurs while incrementing the iterator.key
- either a string or a Buffer depending on the keyAsBuffer
argument when the iterator()
was called.value
- either a string or a Buffer depending on the valueAsBuffer
argument when the iterator()
was called.seek()
is an instance method on an existing iterator object, used to seek the underlying LevelDB iterator to a given key.
By calling seek(key)
, subsequent calls to next(cb)
will return key/values larger or smaller than key
, based on your reverse
setting in the iterator constructor.
end()
is an instance method on an existing iterator object. The underlying LevelDB iterator will be deleted and the callback
function will be called with no arguments if the operation is successful or with a single error
argument if the operation failed for any reason.
destroy()
is used to completely remove an existing LevelDB database directory. You can use this function in place of a full directory rm if you want to be sure to only remove LevelDB-related files. If the directory only contains LevelDB files, the directory itself will be removed as well. If there are additional, non-LevelDB files in the directory, those files, and the directory, will be left alone.
The callback will be called when the destroy operation is complete, with a possible error
argument.
repair()
can be used to attempt a restoration of a damaged LevelDB store. From the LevelDB documentation:
If a DB cannot be opened, you may attempt to call this method to resurrect as much of the contents of the database as possible. Some data may be lost, so be careful when calling this function on a database that contains important information.
You will find information on the repair operation in the LOG file inside the store directory.
A repair()
can also be used to perform a compaction of the LevelDB log into table files.
The callback will be called when the repair operation is complete, with a possible error
argument.
Currently leveldown
does not track the state of the underlying LevelDB instance. This means that calling open()
on an already open database may result in an error. Likewise, calling any other operation on a non-open database may result in an error.
levelup
currently tracks and manages state and will prevent out-of-state operations from being send to leveldown
. If you use leveldown
directly then you must track and manage state for yourself.
leveldown
exposes a feature of LevelDB called snapshots. This means that when you do e.g. createReadStream
and createWriteStream
at the same time, any data modified by the write stream will not affect data emitted from the read stream. In other words, a LevelDB Snapshot captures the latest state at the time the snapshot was created, enabling the snapshot to iterate or read the data without seeing any subsequent writes. Any read not performed on a snapshot will implicitly use the latest state.
There are multiple ways you can find help in using LevelDB in Node.js:
levelup
users in the ##leveldb channel on Freenode, including most of the contributors to this project.leveldown
is an OPEN Open Source Project. This means that:
Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project.
See the contribution guide for more details.
A large portion of the Windows support comes from code by Krzysztof Kowalczyk @kjk, see his Windows LevelDB port here. If you're using leveldown
on Windows, you should give him your thanks!
Copyright © 2012-2017 leveldown
contributors.
leveldown
is licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md
file for more details.
leveldown
builds on the excellent work of the LevelDB and Snappy teams from Google and additional contributors. LevelDB and Snappy are both issued under the New BSD Licence.
FAQs
A low-level Node.js LevelDB binding
The npm package leveldown receives a total of 726,495 weekly downloads. As such, leveldown popularity was classified as popular.
We found that leveldown demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
Security News
A Stanford study reveals 9.5% of engineers contribute almost nothing, costing tech $90B annually, with remote work fueling the rise of "ghost engineers."
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.